package top.revery.account.controller;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.web.bind.annotation.*;
import top.revery.api.config.WxConfig;
import top.revery.api.util.*;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author denghao
 * @title
 * @package
 * @date 2019/12/20 11:12
 */
@RestController
@Slf4j
public class TestController {

    @GetMapping(value = "/app")
    public void getOrder(@RequestParam("money") BigDecimal money, HttpServletResponse response)
            throws Exception {
        BigDecimal a = money.multiply(new BigDecimal(100)).setScale( 0, BigDecimal.ROUND_UP );

        String orderNo = IdUtil.orderNumber();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("appid", WxConfig.APP_ID); // 公众账号ID(配置文件里的属性)
        map.put("mch_id", WxConfig.MCH_ID); // 商户号(配置文件里的属性)
        map.put("device_info", "WEB"); // 设备号(配置文件里的属性)
        map.put("notify_url", WxConfig.NOTIFY_URL); // 异步通知地址(配置文件里的属性)
        map.put("trade_type", "NATIVE"); // 交易类型(表示扫码支付 详情看微信公众平台)
        map.put("out_trade_no", orderNo); // 商户订单号(由项目定)
        map.put("body", WxConfig.BODY); // 商品描述(由项目定)
        map.put("total_fee",a.toString()); // 标价金额(单位 '分')
        // map.put("spbill_create_ip", getRemortIP(request)); // 终端IP(正式环境下用)
        map.put("spbill_create_ip", "58.62.204.131"); // 终端IP(测试环境)
        map.put("nonce_str", PayCommonUtil.getRandomString(30)); // 随机字符串(StringUtil工具类提供)
        map.put("sign", PayCommonUtil.getSign(map)); // 签名(同类中的getSign方法提供)
        String xml = XMLUtil.genXml(map); //发送xml  (XmlUtil工具类提供)
        System.out.println(xml);
        //  return xml;
        String in = HttpClientUtils.send(WxConfig.GATEURL, xml);

        //  InputStream in= HttpClientUtils.sendXMLDataByPost(WxConfig.GATEURL,xml).getEntity().getContent();
        // String code_url = PayCommonUtil.getElementValue(in, "code_url"); // 获取二维码地址(同类中的getElementValue方法提供)
        String code_url = PayCommonUtil.getCodeUrl(in);
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        Map<EncodeHintType, Object> hints = new HashMap();
        BitMatrix bitMatrix = null;
        if (code_url == null || "".equals(code_url)) {

            code_url = "weixin://wxpay/bizpayurl?pr=LGpUoeu";
        }
        try {
            /** 定义LOGO图片的宽度 */
            int LOGO_WIDTH = 50;
            /** 定义LOGO图片的高度 */
            int LOGO_HEIGHT = 50;
            /** 定义Map集合封装二维码配置信息 */
            /** 设置二维码图片的内容编码 */
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
            /** 设置二维码图片的上、下、左、右间隙 */
            hints.put(EncodeHintType.MARGIN, 1);
            /** 设置二维码的纠错级别 */
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);

            bitMatrix = multiFormatWriter.encode(code_url, BarcodeFormat.QR_CODE, 250, 250, hints);
            /** 获取二维码图片真正的宽度  */
            int matrix_width = bitMatrix.getWidth();
            /** 获取二维码图片真正的高度  */
            int matrix_height = bitMatrix.getHeight();
            /** 定义一张空白的缓冲流图片 */
            BufferedImage image = new BufferedImage(matrix_width, matrix_height, BufferedImage.TYPE_INT_RGB);
            /** 把二维码字节转换对象 转化 到缓冲流图片上 */
            for (int x = 0; x < matrix_width; x++) {
                for (int y = 0; y < matrix_height; y++) {
                    /** 通过x、y坐标获取一点的颜色 true: 黑色  false: 白色 */
                    int rgb = bitMatrix.get(x, y) ? 0x050505 : 0xFFFFFF;
                    image.setRGB(x, y, rgb);
                }
            }

            /** 获取公司logo图片 */
            BufferedImage logo = ImageIO.read(new File("C:\\Users\\dell\\Pictures\\1.jpg"));
            /** 获取缓冲流图片的画笔 */
            Graphics2D g = (Graphics2D) image.getGraphics();
            /** 在二维码图片中间绘制公司logo */
            g.drawImage(logo, (matrix_width - LOGO_WIDTH) / 2,
                    (matrix_height - LOGO_HEIGHT) / 2, LOGO_WIDTH, LOGO_HEIGHT, null);

            /** 设置画笔的颜色 */
            g.setColor(Color.WHITE);
            /** 设置画笔的粗细 */
            g.setStroke(new BasicStroke(5.0f));
            /** 设置消除锯齿 */
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            /** 绘制圆角矩形 */
            g.drawRoundRect((matrix_width - LOGO_WIDTH) / 2, (matrix_height - LOGO_HEIGHT) / 2,
                    LOGO_WIDTH, LOGO_HEIGHT, 10, 10);
            //输出二维码图片流
            ImageIO.write(image, "png", response.getOutputStream());

        } catch (WriterException e1) {
            e1.printStackTrace();
        }

    }

    @PostMapping(value = "/wxnotify")
    public String alipayNotify(HttpServletRequest request) throws Exception {
        log.info("==================微信异步返回支付结果开始");
        InputStream inputStream;
        StringBuffer sb = new StringBuffer();
        inputStream = request.getInputStream();
        String s;
        BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        while ((s = in.readLine()) != null) {
            sb.append(s);
        }
        in.close();
        inputStream.close();
        System.out.println("sb:" + sb.toString());

        //解析xml成map
        Map<String, String> map = new HashMap<String, String>();
        try {
            Document doc = DocumentHelper.parseText(sb.toString());
            Element rootElt = doc.getRootElement();
            System.out.println("根节点：" + rootElt.getName());
            Iterator iter = rootElt.elementIterator("head");// 获取根节点下的子节点head
            // 遍历head节点
            while (iter.hasNext()) {
                Element recordEle = (Element) iter.next();
                String title = recordEle.elementTextTrim("title"); // 拿到head节点下的子节点title值
                System.out.println("title:" + title);
                map.put("title", title);
                Iterator iters = recordEle.elementIterator("script"); // 获取子节点head下的子节点script
                // 遍历Header节点下的Response节点
                while (iters.hasNext()) {
                    Element itemEle = (Element) iters.next();
                    String username = itemEle.elementTextTrim("username"); // 拿到head下的子节点script下的字节点username的值
                    String password = itemEle.elementTextTrim("password");
                    System.out.println("username:" + username);
                    System.out.println("password:" + password);
                    map.put("username", username);
                    map.put("password", password);
                }
            }
            Iterator iterss = rootElt.elementIterator("body"); ///获取根节点下的子节点body
            // 遍历body节点
            while (iterss.hasNext()) {
                Element recordEless = (Element) iterss.next();
                String result = recordEless.elementTextTrim("result"); // 拿到body节点下的子节点result值
                System.out.println("result:" + result);
                Iterator itersElIterator = recordEless.elementIterator("form"); // 获取子节点body下的子节点form
                // 遍历Header节点下的Response节点
                while (itersElIterator.hasNext()) {
                    Element itemEle = (Element) itersElIterator.next();
                    String banlce = itemEle.elementTextTrim("banlce"); // 拿到body下的子节点form下的字节点banlce的值
                    String subID = itemEle.elementTextTrim("subID");
                    System.out.println("banlce:" + banlce);
                    System.out.println("subID:" + subID);
                    map.put("result", result);
                    map.put("banlce", banlce);
                    map.put("subID", subID);
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //过滤空 设置 TreeMap
        SortedMap<String, String> packageParams = new TreeMap<String, String>();
        Iterator<String> it = map.keySet().iterator();
        while (it.hasNext()) {
            String parameter = it.next();
            String parameterValue = map.get(parameter);

            String v = "";
            if (null != parameterValue) {
                v = parameterValue.trim();
            }
            packageParams.put(parameter, v);
        }

        if (PayCommonUtil.isTenpaySign(packageParams)) { // 验证通过
            if ("SUCCESS".equals((String) packageParams.get("result_code"))) {
                System.out.println("验证通过");
                //记录

            } else {
                System.out.println("支付失败");
            }
        } else {
            System.out.println("验证未通过");
        }

        return "SUCCESS";

    }

}
